<template>
  <div class="datawarehouse-config">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>数据仓库配置管理</span>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            新增配置
          </el-button>
        </div>
      </template>

      <el-table :data="configs" style="width: 100%">
        <el-table-column prop="name" label="配置名称" width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.type === 'doris' ? 'success' : 'info'">
              {{ scope.row.type.toUpperCase() }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="host" label="主机" width="120" />
        <el-table-column prop="port" label="端口" width="80" />
        <el-table-column prop="database_name" label="数据库" width="120" />
        <el-table-column prop="is_default" label="默认" width="80">
          <template #default="scope">
            <el-tag v-if="scope.row.is_default" type="warning">默认</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
              {{ scope.row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleTestConnection(scope.row)">
              测试连接
            </el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑数据仓库配置' : '新增数据仓库配置'"
      width="600px"
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入配置名称" />
        </el-form-item>
        
        <el-form-item label="数据库类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择数据库类型">
            <el-option label="Apache Doris" value="doris" />
            <el-option label="ClickHouse" value="clickhouse" />
            <el-option label="StarRocks" value="starrocks" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="主机地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入主机地址" />
        </el-form-item>
        
        <el-form-item label="端口" prop="port">
          <el-input-number v-model="form.port" :min="1" :max="65535" placeholder="端口号" />
        </el-form-item>
        
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        
        <el-form-item label="数据库名" prop="database_name">
          <el-input v-model="form.database_name" placeholder="请输入数据库名" />
        </el-form-item>
        
        <el-form-item label="设为默认">
          <el-switch v-model="form.is_default" />
        </el-form-item>
        
        <el-form-item label="启用状态">
          <el-switch v-model="form.is_active" />
        </el-form-item>
        
        <el-form-item label="描述">
          <el-input v-model="form.description" type="textarea" rows="3" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'DatawarehouseConfig',
  components: {
    Plus
  },
  setup() {
    const configs = ref([])
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const submitting = ref(false)
    const formRef = ref()

    const form = reactive({
      id: null,
      name: '',
      type: 'doris',
      host: '',
      port: 9030,
      username: 'root',
      password: '',
      database_name: '',
      is_default: false,
      is_active: true,
      description: ''
    })

    const rules = {
      name: [
        { required: true, message: '请输入配置名称', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择数据库类型', trigger: 'change' }
      ],
      host: [
        { required: true, message: '请输入主机地址', trigger: 'blur' }
      ],
      port: [
        { required: true, message: '请输入端口号', trigger: 'blur' }
      ]
    }

    const fetchConfigs = async () => {
      try {
        const response = await axios.get('/api/datawarehouse/configs')
        configs.value = response.data
      } catch (error) {
        ElMessage.error('获取配置列表失败')
        console.error(error)
      }
    }

    const resetForm = () => {
      Object.assign(form, {
        id: null,
        name: '',
        type: 'doris',
        host: '',
        port: 9030,
        username: 'root',
        password: '',
        database_name: '',
        is_default: false,
        is_active: true,
        description: ''
      })
    }

    const handleCreate = () => {
      resetForm()
      isEdit.value = false
      dialogVisible.value = true
    }

    const handleEdit = (row) => {
      Object.assign(form, { ...row })
      isEdit.value = true
      dialogVisible.value = true
    }

    const handleSubmit = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (!valid) return
        
        submitting.value = true
        try {
          if (isEdit.value) {
            await axios.put(`/api/datawarehouse/configs/${form.id}`, form)
            ElMessage.success('更新成功')
          } else {
            await axios.post('/api/datawarehouse/configs', form)
            ElMessage.success('创建成功')
          }
          
          dialogVisible.value = false
          fetchConfigs()
        } catch (error) {
          ElMessage.error(error.response?.data?.detail || '操作失败')
          console.error(error)
        } finally {
          submitting.value = false
        }
      })
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除配置"${row.name}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        await axios.delete(`/api/datawarehouse/configs/${row.id}`)
        ElMessage.success('删除成功')
        fetchConfigs()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
          console.error(error)
        }
      }
    }

    const handleTestConnection = async (row) => {
      try {
        ElMessage.info('正在测试连接...')
        const response = await axios.post(`/api/datawarehouse/configs/${row.id}/test-connection`)
        if (response.data.success) {
          ElMessage.success('连接测试成功')
        } else {
          ElMessage.error('连接测试失败')
        }
      } catch (error) {
        ElMessage.error('连接测试失败')
        console.error(error)
      }
    }

    onMounted(() => {
      fetchConfigs()
    })

    return {
      configs,
      dialogVisible,
      isEdit,
      submitting,
      formRef,
      form,
      rules,
      handleCreate,
      handleEdit,
      handleSubmit,
      handleDelete,
      handleTestConnection
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 